/**
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
*/

package org.elephantt.webby;

import java.util.StringTokenizer;
import java.util.Map;
import java.util.HashMap;

/**
 * URL-related utilities
 */
public class UrlUtil {
  private static final String[] ZERO_LENGTH_ARRAY = new String[0];

  /**
   * Returns an array of /-separated tokens for a URI path
   */
  public static String[] tokenizePath(String uriPath) {
    String[] tokens;
    if (uriPath != null) {
      StringTokenizer tok = new StringTokenizer(uriPath, "/");
      tokens = new String[tok.countTokens()];
      int i=0;
      while (tok.hasMoreTokens()) {
        tokens[i++] = tok.nextToken();
      }
    } else {
      tokens = ZERO_LENGTH_ARRAY;
    }
    return tokens;
  }

  public static String createQueryString(Map map) {
    return createQueryString(map, new StringBuilder());
  }

  public static String createQueryString(Map map, StringBuilder append) {
    StringBuilder sb;
    if (append != null) {
      sb = append;
    } else {
      sb = new StringBuilder();
    }

    for (Object entry : map.entrySet()) {
      if (sb.length() > 0) {
        sb.append("&");
      }
      Map.Entry mentry = (Map.Entry) entry;
      sb.append(mentry.getKey());
      sb.append("=");
      sb.append(mentry.getValue());
    }

    return sb.toString();
  }

  public static Map<String, String> parseQueryString(String queryString) {
    Map<String, String> map = new HashMap<String, String>();
    String[] pairs = queryString.split("&");
    for (String pair : pairs) {
      String[] pairData = pair.split("=");
      String value;
      if (pairData.length > 1) {
        value = pairData[1];
      } else {
        value = Boolean.TRUE.toString();
      }
      map.put(pairData[0], value);
    }
    return map;
  }
}